package com.zhj.test.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhj
 */
public class BIOServer {

    public static void main(String[] args) throws IOException {
        // 线程池机制

        // 思路
        // 1. 创建一个线程
        // 2. 如果有客户端连接，就创建一个线程，与之通信（单独写一个方法）

        ExecutorService executorService = Executors.newCachedThreadPool();

        // 创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器程序启动！");

        while (true) {
            // 监听，等待客户端连接
            System.out.println("等待连接！！！");
            final Socket socket = serverSocket.accept();
            System.out.println("连接一个客户端（socket）！");

            // 创建一个线程与之通讯
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // 可以与客户端通讯
                    handler(socket);
                }
            });
        }
    }

    /**
     * 与客户端通讯
     */
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            // 循环读取客户端读取的数据
            while (true) {
                System.out.println("等待输入数据！！！");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(Thread.currentThread().getName() + " : " + Thread.currentThread().getId());
                    System.out.println("接收：" + new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭与客户端的连接！");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
